package com.guli.edu.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.handler.EduException;
import com.guli.common.result.ResultCodeEnum;
import com.guli.common.util.ExcelImportHSSFUtil;
import com.guli.edu.entity.EduSubject;
import com.guli.edu.entity.dto.SubjectOneLevel;
import com.guli.edu.entity.dto.SubjectTwoLevel;
import com.guli.edu.mapper.EduSubjectMapper;
import com.guli.edu.service.EduSubjectService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author Daniel
 * @since 2019-03-25
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {


    //poi读取excel
    @Override
    public List<String> importData(MultipartFile file) {

        List<String> msg = new ArrayList<>();
        try{

            //2：创建workbook
            ExcelImportHSSFUtil excelHSSFUtil = new ExcelImportHSSFUtil(file.getInputStream());
            //3:获取sheet
            HSSFSheet sheet = excelHSSFUtil.getSheet();

            //4:获取sheet里面所有的行
            //sheet.getPhysicalNumberOfRows() 索引从1开始
            // sheet.getLastRowNum(); 索引从0开始
            //获取到最后一行索引的位置
            int rowCount  = sheet.getLastRowNum();
            //5:从第二行开始获取数据，添加到表里面

            for (int i = 1; i <= rowCount; i++) {
                //遍历获取每一行
                HSSFRow rowData = sheet.getRow(i);
                if(rowData ==  null){
                    msg.add("表格数据为空,请输入数据");
                    return msg ;
                }
                //如果行里面有数据 获取行里面列
                HSSFCell cellOne = rowData.getCell(0);
                if(cellOne == null){
                    //提示错误信息
                    msg.add("第"+i+"行数据为空");
                    //要继续执行不能返回return
                    continue;
                }
                //cellOne.getStringCellValue() 这样写可能无法判断类型
                //获取类里面数据类型
                int cellType = cellOne.getCellType();
                String oneValue = excelHSSFUtil.getCellValue(cellOne, cellType);
                /***
                 * 判断一节分类在数据库中是否存在，如果不存在添加 如果相同不需要添加
                 */
                 String parentid = null ;
                EduSubject exsisteEduSubject = this.existOneSubject(oneValue);
                if (exsisteEduSubject == null){
                    //不存在一级分类
                    EduSubject eduSubjectOne = new EduSubject();
                    eduSubjectOne.setTitle(oneValue);
                    eduSubjectOne.setParentId("0");
                    eduSubjectOne.setSort(0);
                    baseMapper.insert(eduSubjectOne);
                    parentid = eduSubjectOne.getId();

                }else{
                    //获取一级分类id，作为二级分类parentid值
                    parentid = exsisteEduSubject.getId();
                }
                //获取第二列
                HSSFCell cellTwo = rowData.getCell(1);
                if(cellTwo == null){
                    //提示错误信息
                    msg.add("第"+i+"行数据为空");
                    //要继续执行不能返回return
                    continue;
                }
                int cellTwoCellType = cellTwo.getCellType();
                //获取第二列里面的值
                String twoValue = excelHSSFUtil.getCellValue(cellTwo, cellTwoCellType);

                /***
                 * 判断二级分类在数据库中是否存在
                 */
                final EduSubject existTwoEduSubject = this.existTwoSubject(twoValue, parentid);
                if (existTwoEduSubject == null ){
                    //不存在二级分类
                    EduSubject eduSubjectTwo = new EduSubject();
                    eduSubjectTwo.setTitle(twoValue);
                    eduSubjectTwo.setParentId(parentid);
                    eduSubjectTwo.setSort(0);
                    baseMapper.insert(eduSubjectTwo);
                }
            }
        }catch(Exception  e){
                e.printStackTrace();
            throw new EduException(ResultCodeEnum.EXCEL_DATA_ERROR);
        }
        return msg;
    }



    //判断一级分类是否存在
    private EduSubject existOneSubject(String oneTypeName){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",oneTypeName);
        wrapper.eq("parent_id","0");
        return baseMapper.selectOne(wrapper);
    }

    //判断二级分类是否存在
    private EduSubject existTwoSubject(String twoTypeName,String parentId){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        //eq  =    ne !=
        wrapper.eq("title",twoTypeName);
        wrapper.eq("parent_id",parentId);
        return baseMapper.selectOne(wrapper);

    }

    //返回要求的格式的json数据
    //[{"id":"1","title","前端","children",[{"id":"11","title":"html"}]}]
    @Override
    public List<SubjectOneLevel> getListSubject() {
        //1:获取所有的一级分类
        List<EduSubject> oneLevelAll = this.getOneLevelAll();
        //创建一个List集合 ，用于一级分类dto对象封装
        List<SubjectOneLevel> subjectOneLevelList = new ArrayList<>();
        //把返回所有的一级分类 转换成dto对象 SubjectOneLevel对象
        for (EduSubject oneSubject : oneLevelAll) {
            SubjectOneLevel subjectOneLevel = new SubjectOneLevel();
              //要把oneSubject转化成SubjectOneLevel对象
            BeanUtils.copyProperties(oneSubject,subjectOneLevel);
            //把我们转换之后的对象放到list集合中
            subjectOneLevelList.add(subjectOneLevel);
            //获取所有的二级分类
            List<EduSubject> twoLevelAll = this.getTwoLevelAll();
            //创建集合存储转换之后二级分类的dto对象
            List<SubjectTwoLevel> subjectTwoLevelList = new ArrayList<>();
            //遍历所有的二级分类 得到每个二级分类 转换二级分类dto对象
            for (EduSubject twoSubject : twoLevelAll) {
                //判断当前二级分类是否为上面一级分类里面的
                //判断二级分类parentid 和一级分类id是否一样
                //字符串类型使用equals判断

                if (twoSubject.getParentId().equals(subjectOneLevel.getId()) ) {
                    SubjectTwoLevel subjectTwoLevel = new SubjectTwoLevel();
                    BeanUtils.copyProperties(twoSubject,subjectTwoLevel);
                    subjectTwoLevelList.add(subjectTwoLevel);
                }
            }
            subjectOneLevel.setChildren(subjectTwoLevelList);
        }
        return subjectOneLevelList;
    }

    //添加一级分类
    @Override
    public boolean addLevelOne(EduSubject eduSubject) {
        //判断一级分类是否存在
        EduSubject existSubject = this.existOneSubject(eduSubject.getTitle());
        if(existSubject== null){

            eduSubject.setParentId("0");
            int count = baseMapper.insert(eduSubject);
            return count >0 ;
        }
        return false;
    }

    @Override
    public boolean addLevelTwo(EduSubject eduSubject) {
        //判断二级分类是否存在
        EduSubject existTwoSubject = this.existTwoSubject(eduSubject.getTitle(),eduSubject.getParentId());
        if(existTwoSubject== null){
            int count = baseMapper.insert(eduSubject);
            return count >0 ;
        }
        return false;
    }

    @Override
    public boolean deleteById(String id) {
        //判断一级分类里面是否有二级分类
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);
        if (count>0) {
            return false  ;
        }else{
            int result = baseMapper.deleteById(id);
            return result>0 ;
        }
    }

    //返回所有的一级分类
    private List<EduSubject> getOneLevelAll(){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id","0");
        List<EduSubject> eduSubjects = baseMapper.selectList(wrapper);
        return eduSubjects;
    }

    //返回所有的二级分类
    private List<EduSubject> getTwoLevelAll(){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        //eq: =     ne: !=
        wrapper.ne("parent_id","0");
        List<EduSubject> eduSubjects = baseMapper.selectList(wrapper);
        return eduSubjects;
    }
}
